package com.maozzi.api.logger.aop;

import com.maozzi.api.auth.model.UserInfo;
import com.maozzi.api.auth.util.SsoUtil;
import com.maozzi.api.logger.LogService;
import com.maozzi.api.logger.annotation.SysLogger;
import com.maozzi.api.logger.model.LoggerDTO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 操作记录 切面
 *
 * @author maozi
 */
@Aspect
@Component
public class SysLoggerAspect {

    @Resource
    @Lazy
    private LogService loggerService;

    @Pointcut("@annotation(com.maozzi.api.logger.annotation.SysLogger)")
    public void controllerAspect() {
    }

    @Pointcut("@annotation(com.maozzi.api.logger.annotation.SysLogger)")
    public void serviceAspect() {
    }

    @Before("controllerAspect()")
    public void before(JoinPoint joinPoint) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String ip = request.getRemoteAddr();
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class<?> targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String message = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class<?>[] classes = method.getParameterTypes();
                if (classes.length == arguments.length) {
                    message = method.getAnnotation(SysLogger.class).message();
                    break;
                }
            }
        }

        // 操作人
        String username = "";
        UserInfo userInfo = SsoUtil.get();
        if (Objects.nonNull(userInfo)) {
            username = userInfo.getName();
        }

        loggerService.addLog(new LoggerDTO(ip, username, message));
    }
}
